﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;

namespace Garden.d
{
    public abstract class Datask<T, Tid> : IDisposable
        where T : b.Entitype<Tid>, new()
        where Tid : struct
    {
        protected readonly DbContext _context;

        public Datask(DbContext context)
        {
            this._context = context;
        }

        public virtual IEnumerable<T> GetEntities(Func<T, bool> filter)
        {
            return _context.Set<T>().AsNoTracking().Where(filter);
        }

        public virtual int AddEntity(T entity)
        {
            _context.Set<T>().Add(entity);
            return _context.SaveChanges();
        }
        public virtual int ModifyEntity(T entity)
        {
            _context.Entry(entity).State = EntityState.Modified;
            return _context.SaveChanges();
        }
        public virtual int DeleteEntity(Tid id)
        {
            T entity = _context.Set<T>().Local.FirstOrDefault(et => et.Id.Equals(id));
            if (entity == null)
            {
                entity = new T { Id = id };
            }
            _context.Entry(entity).State = EntityState.Deleted;
            return _context.SaveChanges();
        }

        public void Dispose()
        {
            _context.Dispose();
        }
    }
}
